//
//  ScoreKeeper.swift
//  AppleDemo
//
//  Created by Just 花语 on 2025/10/26.
//
import SwiftUI

struct ScoreKeeperView:View{
    @State private var scoreboard = Scoreboard()
    @State private var startingPoints = 0
    @State private var doesHightestScoreWin = true
    // 按钮节流，防止快速点击增加多个
    @State private var addButtonIsAnimating = false
    @State private var minusButtonIsAnimating = false
    
    var body : some View{
//        官方 Grid 布局实现
        VStack(alignment:.leading){
            Text("Score Keeper")
                .font(.title)
                .bold()
                .padding(.bottom,10)
            SettingsView(startingPoints: $startingPoints,highestScoreWins:$doesHightestScoreWin)
                .disabled(scoreboard.state != .setup)
            Grid{
                GridRow{
                    Text("Player")
                        .bold()
                        .gridColumnAlignment(.leading)
                    Text("Score")
                        .bold()
                }
                ForEach($scoreboard.players){ $player in
                    GridRow{
                        HStack{
                            if scoreboard.winner.contains(player) {
                                Image(systemName: "crown.fill")
                                    .foregroundColor(.yellow)
                                    
                            }
                            TextField("Name", text: $player.name)

                        }
                        Stepper("\(player.score)",value:$player.score)
                            .gridColumnAlignment(.leading)
                    }
                }
            }
            .padding(.vertical,10)
            
            HStack{
                Button("Add Player",systemImage: "plus"){
                    // 节流
                    guard !addButtonIsAnimating else { return }
                    addButtonIsAnimating = true
                    withAnimation {
                        scoreboard.players.append(Player(name: "New Player", score: 0))
                    }
                    //恢复按钮状态
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        addButtonIsAnimating = false
                    }
                }
                .disabled(addButtonIsAnimating)
                
                Spacer()
                Button("Miuse Player",systemImage: "minus"){
                    guard !minusButtonIsAnimating else { return }
                    minusButtonIsAnimating = true
                    withAnimation {
                        _ = scoreboard.players.removeLast()
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        minusButtonIsAnimating = false
                    }
                }
                .disabled(minusButtonIsAnimating || scoreboard.players.isEmpty)
            }
            Spacer()
        }
        .frame(maxWidth: .infinity,alignment: .leading)
        .padding(.leading,20)
        .padding(.trailing,20)

        switch scoreboard.state{
            case .setup:
                Button("Start Game",systemImage: "play.fill"){
                    scoreboard.state = .playing
                    scoreboard.doesHighestScoreWin = doesHightestScoreWin
                    scoreboard.resetScores(to:startingPoints)
                }
            case .playing:
                Button("End Game",systemImage: "stop.fill"){
                    scoreboard.state = .gameOver
                }
            case .gameOver:
                Button("Reset Game",systemImage: "arrow.counterclockwise"){
                    scoreboard.state = .setup
                    scoreboard.resetScores(to: startingPoints)
                }
            
        }
        Rectangle()
            .fill(Color.gray.opacity(0.2))
            .frame(height: 10)
        //      扩展，使用 List 实现重排序
        NavigationStack{
            List{
                ForEach($scoreboard.players){ $player in
                    HStack{
                        TextField("Name", text: $player.name)
                        Stepper("\(player.score)", value: $player.score, in: 0...5)
                    }
                }
                .onMove(perform: move)
                .onDelete(perform: delete)
            }
            .navigationTitle("Score Keeper")
            .toolbar{
                ToolbarItem(placement: .navigationBarTrailing){
                    Button("Add Player",systemImage: "plus"){
                        // 节流
                        guard !addButtonIsAnimating else { return }
                        addButtonIsAnimating = true
                        withAnimation {
                            scoreboard.players.append(Player(name: "New Player", score: 0))
                        }
                        //恢复按钮状态
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            addButtonIsAnimating = false
                        }
                    }
                    .disabled(addButtonIsAnimating)
                }
                ToolbarItem(placement: .navigationBarTrailing){
                    Button("Miuse Player",systemImage: "minus"){
                        guard !minusButtonIsAnimating else { return }
                        minusButtonIsAnimating = true
                        withAnimation {
                            _ = scoreboard.players.removeLast()
                        }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            minusButtonIsAnimating = false
                        }
                    }
                    .disabled(minusButtonIsAnimating || scoreboard.players.isEmpty)
                }
                ToolbarItem(placement: .navigationBarLeading){
                    EditButton()
                }
            }
        }
    }
    //      扩展，使用 List 实现重排序
    func move(from source: IndexSet, to destination: Int) {
        scoreboard.players.move(fromOffsets: source, toOffset: destination)
    }
    func delete(at offsets: IndexSet) {
        scoreboard.players.remove(atOffsets: offsets)
    }
}



#Preview {
        ScoreKeeperView()
}
